import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Animated,
  Platform,
  PermissionsAndroid,
  Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AudioRecorderPlayer, {
  AudioEncoderAndroidType,
  AudioSourceAndroidType,
  AVEncoderAudioQualityIOSType,
  AVEncodingOption,
} from 'react-native-nitro-sound';

interface AudioRecorderProps {
  onRecordComplete: (audioPath: string, duration: number) => void;
  maxDuration?: number; // 最大录制时长（秒）
}

const AudioRecorder: React.FC<AudioRecorderProps> = ({
                                                       onRecordComplete,
                                                       maxDuration = 60,
                                                     }) => {
  const [isRecording, setIsRecording] = useState(false);
  const [recordTime, setRecordTime] = useState('00:00');
  const [recordSecs, setRecordSecs] = useState(0);
  const audioRecorderPlayer = useRef(AudioRecorderPlayer).current;
  const pulseAnim = useRef(new Animated.Value(1)).current;

  useEffect(() => {
    return () => {
      audioRecorderPlayer.removeRecordBackListener();
    };
  }, [audioRecorderPlayer]);

  useEffect(() => {
    if (isRecording) {
      // 录制动画
      Animated.loop(
        Animated.sequence([
          Animated.timing(pulseAnim, {
            toValue: 1.2,
            duration: 1000,
            useNativeDriver: true,
          }),
          Animated.timing(pulseAnim, {
            toValue: 1,
            duration: 1000,
            useNativeDriver: true,
          }),
        ])
      ).start();
    } else {
      pulseAnim.setValue(1);
    }
  }, [isRecording, pulseAnim]);

  const requestPermissions = async () => {
    if (Platform.OS === 'android') {
      try {
        const grants = await PermissionsAndroid.requestMultiple([
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
          PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
        ]);

        if (
          grants['android.permission.WRITE_EXTERNAL_STORAGE'] ===
          PermissionsAndroid.RESULTS.GRANTED &&
          grants['android.permission.READ_EXTERNAL_STORAGE'] ===
          PermissionsAndroid.RESULTS.GRANTED &&
          grants['android.permission.RECORD_AUDIO'] ===
          PermissionsAndroid.RESULTS.GRANTED
        ) {
          return true;
        }
        return false;
      } catch (err) {
        console.warn(err);
        return false;
      }
    }
    return true;
  };

  const onStartRecord = async () => {
    const hasPermission = await requestPermissions();
    if (!hasPermission) {
      Alert.alert('需要麦克风权限才能录音');
      return;
    }

    const path = Platform.select({
      ios: 'audio.m4a',
      android: `${Date.now()}.m4a`,
    });

    const audioSet = {
      AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
      AudioSourceAndroid: AudioSourceAndroidType.MIC,
      AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
      AVNumberOfChannelsKeyIOS: 2,
      AVFormatIDKeyIOS: "aac" as AVEncodingOption,
    };

    try {
      await audioRecorderPlayer.startRecorder(path, audioSet);
      audioRecorderPlayer.addRecordBackListener((e) => {
        const currentSecs = Math.floor(e.currentPosition / 1000);
        setRecordSecs(currentSecs);
        setRecordTime(audioRecorderPlayer.mmssss(e.currentPosition));

        // 自动停止录制
        if (currentSecs >= maxDuration) {
          onStopRecord();
        }
      });
      setIsRecording(true);
    } catch (error) {
      console.error('Start record error:', error);
    }
  };

  const onStopRecord = async () => {
    try {
      const result = await audioRecorderPlayer.stopRecorder();
      audioRecorderPlayer.removeRecordBackListener();
      setIsRecording(false);
      setRecordTime('00:00');

      if (recordSecs > 0) {
        onRecordComplete(result, recordSecs);
      }
      setRecordSecs(0);
    } catch (error) {
      console.error('Stop record error:', error);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.timer}>{recordTime}</Text>

      <TouchableOpacity
        style={styles.recordButton}
        onPress={isRecording ? onStopRecord : onStartRecord}
      >
        <Animated.View
          style={[
            styles.recordButtonInner,
            isRecording && {
              transform: [{ scale: pulseAnim }],
            },
          ]}
        >
          <Icon
            name={isRecording ? 'stop' : 'mic'}
            size={40}
            color="#FFFFFF"
          />
        </Animated.View>
      </TouchableOpacity>

      <Text style={styles.hint}>
        {isRecording ? '点击停止录音' : '点击开始录音'}
      </Text>

      {isRecording && (
        <Text style={styles.maxDuration}>
          最长录制时间：{maxDuration}秒
        </Text>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    padding: 20,
  },
  timer: {
    fontSize: 32,
    fontWeight: 'bold',
    marginBottom: 30,
    color: '#333',
  },
  recordButton: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: '#FF3B30',
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  recordButtonInner: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: '#FF3B30',
    justifyContent: 'center',
    alignItems: 'center',
  },
  hint: {
    marginTop: 20,
    fontSize: 16,
    color: '#666',
  },
  maxDuration: {
    marginTop: 10,
    fontSize: 14,
    color: '#999',
  },
});

export default AudioRecorder;